package entities

import (
	"time"
)

type Feedback struct {
	FeedbackID uint      `json:"feedback_id"`
	Content    string    `json:"content"`
	File       string    `json:"file"`
	Status     string    `json:"status"`
	UserID     uint      `json:"user_id"`
	CreatedAt  time.Time `json:"created_at"`
	UpdatedAt  time.Time `json:"updated_at"`
}

func (f *Feedback) Insert() (*Feedback, error) {

	if err := db.QueryRow(`
		insert into feedbacks (content, file, status, user_id) values($1, $2, $3, $4) RETURNING feedback_id, 
		content, 
		file, 
		status, 
		user_id, 
		created_at, 
		updated_at
	`,
		f.Content,
		f.File,
		f.Status,
		f.UserID).Scan(
		&f.FeedbackID,
		&f.Content,
		&f.File,
		&f.Status,
		&f.UserID,
		&f.CreatedAt,
		&f.UpdatedAt); err != nil {
		return nil, err
	}

	return f, nil
}

func (f *Feedback) GetAll(page, size uint) ([]Feedback, error) {
	rows, err := db.Query(`
		select feedback_id, content, file, status, user_id, created_at, updated_at
		from feedbacks
		order by created_at desc
		limit $1 offset $2`, size, (page-1)*size)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	feedbacks := make([]Feedback, 0)
	for rows.Next() {
		var feedback Feedback
		if err := rows.Scan(&feedback.FeedbackID, &feedback.Content, &feedback.File, &feedback.Status, &feedback.UserID, &feedback.CreatedAt, &feedback.UpdatedAt); err != nil {
			return nil, err
		}
		feedbacks = append(feedbacks, feedback)
	}
	return feedbacks, nil
}

func (f *Feedback) Count() (int64, error) {
	var count int64
	err := db.QueryRow("SELECT COUNT(*) FROM feedbacks").Scan(&count)
	return count, err
}
